package io.xdag.exception;

import java.util.HashMap;
import java.util.Map;

import io.xdag.beans.BaseEnum;

public class BaseException extends RuntimeException {

	private static final long serialVersionUID = 1L;

//	private Logger logger = LoggerFactory.getLogger(BaseException.class);

	private long errorCode;

	protected String detailMessage;
	
	private static Map<Integer,Boolean> customizeMessageMap=new HashMap<Integer, Boolean>();
	
	static {
		//初始化 自定义错误
		BaseEnum<Integer>[] baseEnums=BaseException.Enum.values();
		for (BaseEnum<Integer> baseEnum : baseEnums) {
			customizeMessageMap.put(baseEnum.getCode()+999, true);
		}
		
	}

	protected BaseException(String message, Throwable cause, long errorCode) {
		if (cause != null) {
			this.initCause(cause);
		}
		if(customizeMessageMap.get((int)errorCode)!=null && cause!=null) {
			message=cause.getMessage();
		}
		initCodeMessage(message,errorCode);
	}

	protected void initCodeMessage(String message, long errorCode) {
		this.detailMessage = message;
		this.errorCode = errorCode;
	}

	public BaseException() {
		super();
	}

	public long getErrorCode() {
		return errorCode;
	}

	public String getMessage() {
		return this.detailMessage;
	}

	/**
	 * 根据错误类型生成错误码code（错误码=基础错误码+增量）
	 * @param baseErrorCode 基础错误码（需要在BaseException中注册）
	 * @param increment 根据业务累加的数字序列
	 * @return
	 */
	public static long generateErrorCode(Enum baseErrorCode,long increment){
		return baseErrorCode.getCode()+increment;
	}
	
	public static enum Enum implements BaseEnum<Integer>{
		BASECODE_SYSTEM_EXCEPTION(130000,"系统基础错误码"),		
		BASECODE_IO_EXCEPTION(131000,"IO基础错误码"),	
		CONVERTER_EXCEPTION(132000,"转换错误码"),	
		;

		private Integer code;

		private String text;

		Enum(Integer code, String text) {
	        this.code = code;
	        this.text = text;
	    }

	    public Integer getIntCode()
	    {
	    	return getCode();
	    }
	    public Integer getCode() {
	        return code;
	    }

	    public void setCode(Integer code) {
	        this.code = code;
	    }

	    public String getText() {
	        return text;
	    }

	    public void setText(String text) {
	        this.text = text;
	    }
	    
	    @Override
	    public String toString() {
	        return text;
	    }
		
	}
}
